package com.aiti.lulian.service.impl;
/**
 * @Author chenxianzhen
 * @create 2024/6/13 10:39
 */

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.LuLianDockingMeetingDetailsDto;
import com.aiti.lulian.entity.LuLianDockingMeetingAgenda;
import com.aiti.lulian.entity.LuLianDockingMeetingDetails;
import com.aiti.lulian.entity.LuLianGys;
import com.aiti.lulian.entity.LulianActivty;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.LuLianActivityMapper;
import com.aiti.lulian.mapper.LuLianDockingMeetingAgendaMapper;
import com.aiti.lulian.mapper.LuLianDockingMeetingDetailsMapper;
import com.aiti.lulian.mapper.LuLianGysMapper;
import com.aiti.lulian.service.ILulianActivityService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName LuLianActivityServiceImpl
 * @Description TODO
 * @Author chenxianzhen
 * @Date 2024/6/13 10:39
 */
@Service
public class LuLianActivityServiceImpl implements ILulianActivityService {
    @Resource
    LuLianActivityMapper luLianActivityMapper;
    @Resource
    LuLianGysMapper luLianGysMapper;

    @Autowired
    private LuLianDockingMeetingAgendaMapper agendaMapper;

    @Autowired
    private LuLianDockingMeetingDetailsMapper detailsMapper;

    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;


    @Override
    public List<LulianActivty> getHomeData(String baseId) {
        return luLianActivityMapper.getHomeData(baseId);
    }

    @Override
    public void saveGys(LuLianGys luLianGys) {
        luLianGysMapper.insert(luLianGys);
    }

    /**
     * 创建线下活动
     * @param details 活动信息
     * @param userId 操作人Id
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message createLineDownActivity(LuLianDockingMeetingDetails details,String userId) {

        if(StringUtils.isNotBlank(details.getBaseId())){
            return Message.fail("存在主键，请走更新接口");
        }

        //生成详情主键
        String detailId = IdUtil.simpleUUID();
        details.setBaseId(detailId);

        details.setBaseCreateTime(new Date());
        details.setBaseUpdateTime(new Date());
        details.setBaseCreateBy(userId);
        details.setBaseUpdateBy(userId);
        //设置活动为审核中  -- 现在默认为审核通过 0：审核中，1：审核通过
//        details.setMeetingStatus("0");
        details.setMeetingStatus("1");

        //保存Detail信息
        detailsMapper.insert(details);

        List<LuLianDockingMeetingAgenda> agendaList = details.getAgendaList();
        if(agendaList != null && !agendaList.isEmpty()){
            for(LuLianDockingMeetingAgenda item : agendaList){
                item.setAgendaBaseId(IdUtil.simpleUUID());
                item.setMeetingId(detailId);
            }
            //保存活动流程信息
            agendaMapper.batchInsert(agendaList);
        }

        return Message.success("保存成功");
    }

    @Override
    public Message getLineDownActivityById(String lineDownId, String userId) {
        if(StringUtils.isBlank(userId)){
            return Message.fail("没有找到查询信息");
        }
        LuLianDockingMeetingDetails luLianDockingMeetingDetails = detailsMapper.selectOne(new QueryWrapper<LuLianDockingMeetingDetails>().eq("base_id", lineDownId));
        if(luLianDockingMeetingDetails == null){
            return Message.success();
        }
        List<LuLianDockingMeetingAgenda> meetingAgendaList = agendaMapper.selectList(new QueryWrapper<LuLianDockingMeetingAgenda>()
                .eq("meeting_id", luLianDockingMeetingDetails.getBaseId())
                .orderByAsc("start_time"));
        if(meetingAgendaList != null && !meetingAgendaList.isEmpty()){

            List<Map<String, Object>> collect = meetingAgendaList.stream().map(p -> {
                Map<String, Object> temp = new HashMap<>(16);
                Date startTimeDate = p.getStartTime();
                Date endTimeDate = p.getEndTime();
                //格式化时间成前端需要的 HH:mm
                String startTime = DateUtil.format(startTimeDate, "HH:mm");
                String endTime = DateUtil.format(endTimeDate, "HH:mm");
                temp.put("startTime",startTime);
                temp.put("endTime",endTime);

                //其它属性取出重新放到Map中
                String description = p.getDescription();
                temp.put("description", description);
                String meetingId = p.getMeetingId();
                temp.put("meetingId", meetingId);
                String agendaBaseId = p.getAgendaBaseId();
                temp.put("agendaBaseId", agendaBaseId);
                return temp;
            }).collect(Collectors.toList());
            luLianDockingMeetingDetails.setRespDates(collect);
        }
        return Message.success(luLianDockingMeetingDetails);
    }

    /**
     * 修改线下活动数据
     * @param details 详情
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message updateLineDownActivity(LuLianDockingMeetingDetails details,String userId) {
        if(StringUtils.isBlank(details.getBaseId())){
            return Message.fail("没有找到主键");
        }

        //如果入参对象中的状态有值，则代表审核操作（审核通过或审核驳回），按传入的值修改活动的状态
        if (StrUtil.isNotBlank(details.getMeetingStatus()) && (StrUtil.equals(details.getMeetingStatus(), "1") || StrUtil.equals(details.getMeetingStatus(), "4"))){
            LambdaUpdateWrapper<LuLianDockingMeetingDetails> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(LuLianDockingMeetingDetails::getBaseId, details.getBaseId());
            wrapper.set(LuLianDockingMeetingDetails::getMeetingStatus, details.getMeetingStatus());
            if (StrUtil.equals(details.getMeetingStatus(), "4") && StrUtil.isNotEmpty(details.getBhYy())) {
                wrapper.set(LuLianDockingMeetingDetails::getBhYy, details.getBhYy());
            }
            int res = detailsMapper.update(null, wrapper);
            if (res > 0) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } else {
            //通过Id查询出该活动的信息
            LuLianDockingMeetingDetails dbMeetingInfo = detailsMapper.selectOne(new QueryWrapper<LuLianDockingMeetingDetails>()
                    .select("meeting_status")
                    .eq("base_id", details.getBaseId())
                    .eq("base_create_by", userId));

            //0:审核中;4:驳回
            if(!(StringUtils.equals("0", dbMeetingInfo.getMeetingStatus()) || StringUtils.equals("4", dbMeetingInfo.getMeetingStatus()))){
                return Message.fail("非审核中、驳回状态的活动不可修改活动信息");
            }

            //如果该活动的状态不是审核中或者是已驳回不可修改


            details.setBaseUpdateTime(new Date());
            details.setBaseUpdateBy(userId);
            //修改后的状态更改成审核中
            details.setMeetingStatus("0");
            details.setBhYy("");

            detailsMapper.updateById(details);

            //删除所有的活动流程
            agendaMapper.delete(new QueryWrapper<LuLianDockingMeetingAgenda>().eq("meeting_id", details.getBaseId()));
            List<LuLianDockingMeetingAgenda> agendaList = details.getAgendaList();
            if(agendaList != null && !agendaList.isEmpty()){
                for(LuLianDockingMeetingAgenda item : agendaList){
                    item.setAgendaBaseId(IdUtil.simpleUUID());
                    item.setMeetingId(details.getBaseId());
                }
                //保存活动流程信息
                agendaMapper.batchInsert(agendaList);
            }

            return Message.success("修改成功，等待管理员审核");
        }
    }

    /**
     * 分页查询线下活动
     *
     * @param page
     * @param detailsDto
     * @return
     */
    @Override
    public Page<LuLianDockingMeetingDetails> getPageLineDownActivityList(Page<LuLianDockingMeetingDetails> page, LuLianDockingMeetingDetailsDto detailsDto) {
        QueryWrapper<LuLianDockingMeetingDetails> queryWrapper = new QueryWrapper<LuLianDockingMeetingDetails>();

        if(StringUtils.isNotBlank(detailsDto.getActivityName())){
            queryWrapper.eq("activity_name", detailsDto.getActivityName());
        }
        return detailsMapper.selectPage(page, queryWrapper);
    }


    @Override
    public List<LuLianDockingMeetingDetails> queryCurrentUserActivitiesPage(Page<LuLianDockingMeetingDetails> page, String userId, LuLianDockingMeetingDetailsDto details) {

        String roleIds = details.getRoleIds();

        if(StringUtils.isNotBlank(roleIds)){
            String[] split = roleIds.split(",");

            //省级角色
            if(ArrayUtil.containsAny(split,"4ff234fceaa3498aa4058d9dcc130a6b")){
                userId = "";
            }else if(ArrayUtil.containsAny(split,"070cb839a3194e76876ca83b6b181881")){
                //市级角色
                Message userList = cloudShowManagerSubService.getUserList(userId);
                if(userList.getCode() == 1){
                    throw new RuntimeException("没有找到该用户信息");
                }
                List<LinkedHashMap> list = (List<LinkedHashMap>)userList.getObj();
                if(list != null && !list.isEmpty()){
                    LinkedHashMap linkedHashMap = list.get(0);
                    if(linkedHashMap != null && !linkedHashMap.isEmpty()){
                        String cityId = (String)linkedHashMap.get("city");
                        //重置用户Id
                        userId = "";
                        details.setCity(cityId);
                    }
                }
            }
        }
        List<LuLianDockingMeetingDetails> luLianDockingMeetingDetailsPage = detailsMapper.findPage(page, details,userId);
        return luLianDockingMeetingDetailsPage;
    }

    /**
     * 查询当前用户报名中的活动
     *
     * @param userId 用户Id
     * @return
     */
    @Override
    public List<LuLianDockingMeetingDetails> queryCurrentUserActivities(String userId,String roleIds) {

        String nowDateStr = DateUtil.format(new Date(), "yyyy-MM-dd");
        QueryWrapper<LuLianDockingMeetingDetails> qw = new QueryWrapper<LuLianDockingMeetingDetails>()
                .select("base_id", "activity_name")
                .eq("meeting_status", "1")
                .and(i -> i.le("entry_start_time", DateUtil.parse(nowDateStr, "yyyy-MM-dd")).ge("entry_end_time", DateUtil.parse(nowDateStr, "yyyy-MM-dd")));

        if(StringUtils.isNotBlank(roleIds)){
            String[] split = roleIds.split(",");
            if(!ArrayUtil.containsAny(split,"4ff234fceaa3498aa4058d9dcc130a6b")){
                qw.eq("base_create_by", userId);
            }
        }else{
            qw.eq("base_create_by", userId);
        }

        List<LuLianDockingMeetingDetails> meetingDetailsList = detailsMapper.selectList(qw);
        return meetingDetailsList;
    }
}
